﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace XFGameFramework
{

    public static class ColorExtensions
    {

        public static float InverseLerp(Color from, Color to, Color current)
        {

            Vector4 from_color = new Vector4(from.r, from.g, from.b, from.a);
            Vector4 to_color = new Vector4(to.r, to.g, to.b, to.a); 
            Vector4 current_color = new Vector4(current.r,current.g,current.b,current.a);

            float lerp = Mathf.InverseLerp(from_color.x, to_color.x, current_color.x);

            if (lerp > 0 && lerp <= 1)
            { 
                if (Vector4.Distance(current_color, Vector4.Lerp(from_color, to_color, lerp)) <= 0.01f)
                    return lerp;
            }

            lerp = Mathf.InverseLerp(from_color.y, to_color.y, current_color.y);

            if (lerp > 0 && lerp <= 1)
            {
                if (Vector4.Distance(current_color, Vector4.Lerp(from_color, to_color, lerp)) <= 0.01f)
                    return lerp;
            }

            lerp = Mathf.InverseLerp(from_color.z, to_color.z, current_color.z);

            if (lerp > 0 && lerp <= 1)
            {
                if (Vector4.Distance(current_color, Vector4.Lerp(from_color, to_color, lerp)) <= 0.01f)
                    return lerp;
            }

            lerp = Mathf.InverseLerp(from_color.w, to_color.w, current_color.w);

            if (lerp > 0 && lerp <= 1)
            {
                if (Vector4.Distance(current_color, Vector4.Lerp(from_color, to_color, lerp)) <= 0.01f)
                    return lerp;
            }

            return 0;
        }

    }

}

